<template>
  <div>
    <div class="container createProduct">
      <cardVForm ref="cardH" @changeCardV="changeCardH" />
      <cardVForm ref="cardV" @changeCardV="changeCardV" />
      <div style="padding: 20px 0 0 20px">
        <el-button @click="backPage">{{
          $t("createProduct.toBack")
        }}</el-button>
      </div>
      <div class="content">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="228px"
        >
          <div class="title">{{ $t("createProduct.title1") }}</div>
          <el-form-item
            label-width="228px"
            prop="type"
            key="type"
            :label="$t('createProduct.productType')"
            required
          >
            <el-select v-model="ruleForm.type">
              <el-option
                v-for="(item, index) in types"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <template v-if="ruleForm.type === 'type0'">
            <el-form-item
              label-width="228px"
              :label="$t('createProduct.cardDirection')"
            >
              <el-checkbox-group v-model="ruleForm.cardDirectionH">
                <el-checkbox :label="$t('createProduct.horizontal')" />
              </el-checkbox-group>
            </el-form-item>
            <template v-if="ruleForm.cardDirectionH.length > 0">
              <el-form-item
                label-width="228px"
                prop="cardColorH"
                key="cardColorH"
                :label="$t('createProduct.ccri')"
                required
              >
                <div class="cards">
                  <div
                    v-for="(item, index) in ruleForm.cardsH"
                    :key="index"
                    class="demo"
                  >
                    <el-checkbox
                      @change="changeCardsH(index)"
                      :checked="item.checked"
                      :label="item.label"
                    >
                      <div class="left">{{ item.label }}</div>
                    </el-checkbox>
                    <div class="card_h">
                      <el-image
                        v-if="item.src === '1'"
                        style="width: 100%; height: 100%"
                        :src="lockCards[0]"
                        fit="contain"
                      />
                      <el-image
                        v-else
                        style="width: 100%; height: 100%"
                        :src="item.src"
                        fit="contain"
                      />
                    </div>
                  </div>
                  <div>
                    <el-button
                      plain
                      type="primary"
                      icon="el-icon-plus"
                      @click="addCardH"
                      >Add</el-button
                    >
                  </div>
                </div>
              </el-form-item>
              <el-form-item
                label-width="228px"
                prop="logoH"
                key="logoH"
                :label="$t('createProduct.logo')"
                required
              >
                <logoForm
                  v-if="ruleForm.logoH === '1'"
                  :image="lockCards[1]"
                  @changeImage="changeImageH"
                />
                <logoForm
                  v-else
                  :image="ruleForm.logoH"
                  @changeImage="changeImageH"
                />
              </el-form-item>
            </template>

            <el-form-item
              label-width="228px"
              :label="$t('createProduct.direction')"
            >
              <el-checkbox-group v-model="ruleForm.cardDirectionV">
                <el-checkbox :label="$t('createProduct.vertical')" />
              </el-checkbox-group>
            </el-form-item>
            <template v-if="ruleForm.cardDirectionV.length > 0">
              <el-form-item
                prop="cardColorV"
                key="cardColorV"
                :label="$t('createProduct.ccri')"
                label-width="228px"
                required
              >
                <div class="cards">
                  <div
                    v-for="(item, index) in ruleForm.cardsV"
                    :key="index"
                    class="demo"
                  >
                    <el-checkbox
                      @change="changeCardsV(index)"
                      :label="item.label"
                      :checked="item.checked"
                    >
                      <div class="left">{{ item.label }}</div>
                    </el-checkbox>
                    <div class="card_v">
                      <el-image
                        style="width: 100%; height: 100%"
                        :src="item.src"
                        fit="contain"
                      />
                    </div>
                  </div>
                  <div>
                    <el-button
                      plain
                      type="primary"
                      icon="el-icon-plus"
                      @click="addCardV"
                      >Add</el-button
                    >
                  </div>
                </div>
              </el-form-item>
              <el-form-item
                label-width="228px"
                prop="logoV"
                key="logoV"
                :label="$t('createProduct.logo')"
                required
              >
                <logoForm :image="ruleForm.logoV" @changeImage="changeImageV" />
              </el-form-item>
            </template>
          </template>

          <div class="title">{{ $t("createProduct.title2") }}</div>
          <el-form-item
            prop="productName"
            key="productName"
            :label="$t('createProduct.productName')"
            required
          >
            <el-input
              v-model="ruleForm.productName"
              :placeholder="$t('createProduct.nameTip')"
            />
          </el-form-item>
          <el-form-item :label="$t('createProduct.productDescription')">
            <el-input v-model="ruleForm.productDescription" />
            <p style="margin: 0; color: #c0c4cc">
              {{ $t("createProduct.productDescriptionTip") }}
            </p>
          </el-form-item>
          <el-form-item :label="$t('goods.productGroup')">
            <el-select v-model="ruleForm.groupId" multiple>
              <el-option
                v-for="(item, index) in productGroupList"
                :key="index"
                :label="item.groupName"
                :value="item.id"
                :disabled="item.status.label == 'Disable'"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="img"
            key="img"
            :label="$t('createProduct.coverImage')"
            required
          >
            <logoForm
              :image="ruleForm.img + ''"
              @changeImage="changeImageCover"
            />
          </el-form-item>
          <el-form-item :label="$t('createProduct.detailsImage')">
            <logoForm
              :image="ruleForm.detailsImage"
              @changeImage="changeImageDetail"
            />
          </el-form-item>
          <div class="title">{{ $t("createProduct.title3") }}</div>
          <el-form-item
            prop="productPrice"
            key="productPrice"
            :label="$t('createProduct.productPrice')"
            required
          >
            <el-input v-model="ruleForm.productPrice" style="width: 200px" />
            <span style="margin-left: 12px">{{ $t("createProduct.USD") }}</span>
          </el-form-item>
          <el-form-item label-width="0" style="margin-left: 50px">
            <el-checkbox v-model="ruleForm.checked1">
              {{ $t("createProduct.priceTip1") }}
              <span class="sizeFont">{{ $t("createProduct.priceTip2") }}</span>
            </el-checkbox>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.checked1"
            :label="$t('createProduct.discountPrice')"
            prop="discountPrice"
            key="discountPrice"
            required
          >
            <el-input v-model="ruleForm.discountPrice" style="width: 200px" />
            <span style="margin-left: 12px">{{ $t("createProduct.USD") }}</span>
          </el-form-item>
          <el-form-item label-width="0" style="margin-left: 50px">
            <el-checkbox v-model="ruleForm.checked2">{{
              $t("createProduct.priceTip3")
            }}</el-checkbox>
          </el-form-item>
          <div v-if="ruleForm.checked2">
            <el-form-item
              required
              prop="taxRate"
              key="taxRate"
              label="Tax rate"
            >
              <el-input v-model="ruleForm.taxRate" style="width: 200px" />
              <span style="margin-left: 12px">%</span>
            </el-form-item>
            <el-form-item label="Shipping">
              <el-input v-model="ruleForm.shipping" style="width: 200px" />
              <span style="margin-left: 12px">{{
                $t("createProduct.USD")
              }}</span>
            </el-form-item>
          </div>

          <div v-if="id === undefined" style="margin-left: 50px">
            <el-tooltip
              class="item"
              effect="dark"
              :content="$t('createProduct.draftTip')"
              placement="top-start"
            >
              <el-button plain @click="saveDraft('ruleForm')">{{
                $t("createProduct.draft")
              }}</el-button>
            </el-tooltip>

            <el-button type="primary" @click="submitForm('ruleForm')">{{
              $t("createProduct.create")
            }}</el-button>
          </div>
          <div v-else style="margin-left: 50px">
            <el-button type="primary" plain @click="submitForm('ruleForm')">{{
              $t("createProduct.Save")
            }}</el-button>
            <el-button
              v-if="ruleForm.status && ruleForm.status.value === 'status1'"
              type="primary"
              @click="submitForm0('ruleForm')"
              >{{ $t("createProduct.create") }}</el-button
            >
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import Tinymce from "@/components/Tinymce";
import {
  addCommodity,
  getCommodityById,
  getCommodityList,
  setCommodity,
} from "@/api/commodity";
import {
  getProductGroupList,
  addGroup,
  setListGroup,
} from "@/api/productGroup";
import cardVForm from "./cardVForm";
import logoForm from "@/components/logoForm";
export default {
  components: { Tinymce, cardVForm, logoForm },
  data() {
    return {
      cardsH: [],
      cardsV: [],
      predefine: [
        "#409EFF",
        "#1890ff",
        "#304156",
        "#212121",
        "#11a983",
        "#13c2c2",
        "#6959CD",
        "#f5222d",
      ],
      cardsHList: [],
      cardsVList: [],
      types: this.storage.get("types"),
      ruleForm: {
        detailsImage: "",
        img: "",
        cardDirectionH: [],
        cardDirectionV: [],
        cardColor: [],
        cardsVList: [],
        // 选择图片颜色
        cardColorH: [],
        cardColorV: [],
        cardsH: [],
        cardsV: [],
        logoH: "",
        logoV: "",
        listH: [],
        listV: [],
        listCover: [],
        productName: "",
      },
      imageUrl: "",
      dialogImageUrl: "",
      dialogVisible: false,
      content: "",
      rules: {
        img: [
          {
            required: true,
            message: this.$t("rulesProduct.img"),
            trigger: "change",
          },
        ],
        detailsImage: [
          {
            required: true,
            message: this.$t("rulesProduct.detailsImage"),
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: this.$t("rulesProduct.type"),
            trigger: "blur",
          },
        ],
        cardDirectionH: [
          {
            type: "array",
            required: true,
            message: this.$t("rulesProduct.cardDirectionH"),
            trigger: "change",
          },
        ],
        cardDirectionV: [
          {
            type: "array",
            required: true,
            message: this.$t("rulesProduct.cardDirectionV"),
            trigger: "change",
          },
        ],
        cardColorH: [
          {
            required: true,
            message: this.$t("rulesProduct.cardColorH"),
            trigger: "change",
          },
        ],
        cardColorV: [
          {
            required: true,
            message: this.$t("rulesProduct.cardColorV"),
            trigger: "change",
          },
        ],
        logoH: [
          {
            required: true,
            message: this.$t("rulesProduct.logoH"),
            trigger: "blur",
          },
        ],
        logoV: [
          {
            required: true,
            message: this.$t("rulesProduct.logoV"),
            trigger: "blur",
          },
        ],
        cardsVList: [
          {
            required: true,
            message: this.$t("rulesProduct.cardsVList"),
            trigger: "blur",
          },
        ],
        productName: [
          {
            required: true,
            message: this.$t("rulesProduct.productName"),
            trigger: ["change", "blur"],
          },
        ],
        productAttributes: [
          {
            required: true,
            message: this.$t("rulesProduct.productAttributes"),
            trigger: "blur",
          },
        ],
        productPrice: [
          {
            required: true,
            message: this.$t("rulesProduct.productPrice"),
            trigger: "blur",
          },
        ],
        discountPrice: [
          {
            required: true,
            message: this.$t("rulesProduct.discountPrice"),
            trigger: "blur",
          },
        ],
        taxRate: [
          {
            required: true,
            message: this.$t("rulesProduct.taxRate"),
            trigger: "blur",
          },
        ],
      },
      id: null,
      productGroupList: [],
      lockCards: [
        require("@/assets/img/H-W.png"),
        require("@/assets/img/th.jpg"),
      ],
      oldGroupId: null, //旧分组id
    };
  },
  created() {
    this.cacheGroup();
    this.id = this.$route.query.id;
    this.getCommodityLength();
    if (this.id !== undefined) {
      this.init();
    }
  },
  methods: {
    changeCardsH(index) {
      this.ruleForm.cardsH = this.ruleForm.cardsH.map((item, num) => {
        if (num == index) {
          item.checked = !item.checked;
        }
        return item;
      });
      let isCheck = this.ruleForm.cardsH.filter((item) => item.checked);
      if (isCheck.length == 0) {
        this.ruleForm.cardColorH = "";
      } else {
        this.ruleForm.cardColorH = true;
      }
    },
    changeCardsV(index) {
      this.ruleForm.cardsV = this.ruleForm.cardsV.map((item, num) => {
        if (num == index) {
          item.checked = !item.checked;
        }
        return item;
      });
      let isCheck = this.ruleForm.cardsV.filter((item) => item.checked);
      if (isCheck.length == 0) {
        this.ruleForm.cardColorV = "";
      } else {
        this.ruleForm.cardColorV = true;
      }
    },
    // 总共产品数量
    async getCommodityLength() {
      const res = await getCommodityList({
        page: 1,
        limit: 9999,
        name: "",
        type: "",
        groupId: "",
        status: "",
      });
      this.storage.set("commodityLength", res.data.length);
    },
    async init() {
      const res = await getCommodityById({ id: this.id });
      res.data.type = res.data.type ? res.data.type.value : "";
      res.data.listH = [{ url: res.data.logoH }];
      res.data.listV = [{ url: res.data.logoV }];
      res.data.listCover = [{ url: res.data.img }];
      res.data.listDetail = res.data.detailsImage
        ? [{ url: res.data.detailsImage }]
        : [];

      res.data.productName = res.data.name ? res.data.name : "";
      res.data.productPrice = res.data.price ? res.data.price : "";

      const imgList = this.storage.get("imgList") || [];
      const list = imgList.filter((item) => item.id + "" === this.id + "");
      if (list.length > 0) {
        const { cardsH, cardsV, detailsImage, logoH, logoV, img } = list[0];
        res.data.cardsH = cardsH;
        res.data.cardsV = cardsV;
        res.data.detailsImage = detailsImage;
        res.data.logoH = logoH;
        res.data.logoV = logoV;
        res.data.img = img;
      }
      console.log("list===", list);
      this.ruleForm = res.data;
      if (this.ruleForm.cardsH === "cardsH") {
        this.ruleForm.cardsH = "";
      }
      if (this.ruleForm.cardsV === "cardsV") {
        this.ruleForm.cardsV = "";
      }
      if (this.ruleForm.detailsImage === "detailsImage") {
        this.ruleForm.detailsImage = "";
      }
      if (this.ruleForm.logoH === "logoH") {
        this.ruleForm.logoH = "";
      }
      if (this.ruleForm.logoV === "logoV") {
        this.ruleForm.logoV = "";
      }
      this.oldGroupId = res.data.groupId;
      if (this.ruleForm.cardDirectionH.length > 0) {
        this.ruleForm.cardColorH = true;
      }
      if (this.ruleForm.cardDirectionV.length > 0) {
        this.ruleForm.cardColorV = true;
      }
      console.log("通过id获取==", this.ruleForm);
    },
    // 卡的竖直向封面
    changeCardV(e) {
      console.log("e===", e);
      if (e) {
        this.ruleForm.cardsV = [...this.ruleForm.cardsV, e];
      }
      this.$refs.cardV.close();
    },
    addCardV() {
      this.$refs.cardV.show();
    },
    changeImageV(e) {
      this.ruleForm.logoV = e;
    },
    // 卡的横向封面
    changeImageH(e) {
      this.ruleForm.logoH = e;
    },
    changeCardH(e) {
      if (e) {
        this.ruleForm.cardsH = [...this.ruleForm.cardsH, e];
      }
      this.$refs.cardH.close();
    },
    addCardH() {
      console.log("ruleForm.cardsH====", this.ruleForm.cardsH);
      this.$refs.cardH.show();
    },

    backPage() {
      // 关闭当前路由，返回上级路由
      // this.$store.state.tagsView.visitedViews.splice(
      //   this.$store.state.tagsView.visitedViews.findIndex(
      //     (item) => item.path === this.$route.path
      //   ),
      //   1
      // );
      this.$router.push("/commodityManagement/list");
    },
    isCheckFn() {
      console.log("ruleForm=======", this.ruleForm);
      if (!this.ruleForm.checked1) {
        this.ruleForm.discountPrice = "";
      }
      if (!this.ruleForm.checked2) {
        this.ruleForm.taxRate = "";
        this.ruleForm.shipping = "";
      }
    },
    // 保存草稿
    saveDraft(formName) {
      this.ruleForm.status = JSON.stringify({
        value: "status3",
        label: "Draft",
      });
      this.submitForm(formName);
    },
    submitForm(formName) {
      if (this.id === undefined) {
        this.createForm(formName);
      } else {
        this.editForm(formName);
      }
    },
    // 未上架商品
    submitForm0(formName) {
      this.ruleForm.status = { value: "status0", label: "On sale" };
      this.editForm(formName);
      console.log("返回上一页");
      this.$router.push("/commodityManagement/list");
    },
    async createForm(formName) {
      var that = this;
      console.log("this.ruleForm====", this.ruleForm);
      const { cardsH, cardsV, detailsImage, logoH, logoV, img } = this.ruleForm;
      let imgList =
        this.storage.get("imgList") || this.storage.set("imgList", []);
      if (
        this.ruleForm.type === "type0" &&
        this.ruleForm.cardDirectionH.length === 0 &&
        this.ruleForm.cardDirectionV.length === 0
      ) {
        this.$message.error(this.$t("createProduct.error0"));
        return false;
      }
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.$confirm(
            this.$t("createProduct.onSaleTip"),
            this.$t("rulesManagement.tip"),
            {
              confirmButtonText: this.$t("rulesManagement.confirm"),
              cancelButtonText: this.$t("rulesManagement.cancel"),
              type: "warning",
            }
          )
            .then(async () => {
              if (
                parseInt(this.ruleForm.discountPrice) >=
                parseInt(this.ruleForm.productPrice)
              ) {
                this.$message.error(this.$t("createProduct.error3"));
                return false;
              }

              this.ruleForm.cardColor = this.ruleForm.cardColor.toString();
              this.ruleForm.cardsVList = this.ruleForm.cardsVList.toString();
              const addForm = JSON.parse(JSON.stringify(this.ruleForm));
              addForm.cardsH = "cardsH";
              addForm.cardsV = "cardsV";
              addForm.detailsImage = "detailsImage";
              addForm.logoH = "logoH";
              addForm.logoV = "logoV";
              addForm.img = "img";
              await addCommodity(addForm);
              // 图片缓存到本地
              const obj = { cardsH, cardsV, detailsImage, logoH, logoV, img };
              obj.id = this.storage.get("commodityLength") + "";
              imgList.push(obj);
              this.storage.set("imgList", imgList);

              await that.addProductGroup();
              console.log("返回上一页");
              this.$router.push("/commodityManagement/list");
            })
            .catch((err) => {
              console.log("err======", err);
              if (err.toString().indexOf("Storage") != -1) {
                this.$message({
                  type: "warning",
                  message: "Out of Memory!",
                });
              }
            });

          // alert("submit!");
        } else {
          return false;
        }
      });
    },
    async editForm(formName) {
      console.log("this.ruleForm====", this.ruleForm);
      if (this.ruleForm.productName == "") {
        this.ruleForm.productName = null;
      }
      const { cardsH, cardsV, detailsImage, logoH, logoV, img } = this.ruleForm;
      let imgList =
        this.storage.get("imgList") || this.storage.set("imgList", []);

      if (
        this.ruleForm.type === "type0" &&
        this.ruleForm.cardDirectionH.length === 0 &&
        this.ruleForm.cardDirectionV.length === 0
      ) {
        this.$message.error("Please select Horizontal or Vertical");
        return false;
      }
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (
            parseInt(this.ruleForm.discountPrice) >=
            parseInt(this.ruleForm.productPrice)
          ) {
            this.$message.error(this.$t("createProduct.error3"));
            return false;
          }
          this.isCheckFn();
          // this.ruleForm.cardColor = this.ruleForm.cardColor.toString();
          // this.ruleForm.cardsVList = this.ruleForm.cardsVList.toString();
          const addForm = JSON.parse(JSON.stringify(this.ruleForm));
          addForm.cardsH = "cardsH";
          addForm.cardsV = "cardsV";
          addForm.detailsImage = "detailsImage";
          addForm.logoH = "logoH";
          addForm.logoV = "logoV";
          addForm.img = "img";
          await setCommodity(addForm);
          // 图片缓存到本地
          imgList = imgList.map((item) => {
            if (item.id + "" == this.id + "") {
              item = {
                id: item.id,
                cardsH,
                cardsV,
                detailsImage,
                logoH,
                logoV,
                img,
              };
            }
            return item;
          });
          const num = imgList.filter((item) => item.id + "" === this.id + "")
            .length;
          if (num === 0) {
            const obj = {
              id: this.id,
              cardsH,
              cardsV,
              detailsImage,
              logoH,
              logoV,
              img,
            };
            imgList.push(obj);
            console.log("obj==========", obj);
          }
          this.storage.set("imgList", imgList);
          this.changeGroup();
          console.log("返回上一页");
          this.$router.push("/commodityManagement/list");
          // alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 添加新产品组里面的产品id
    async addProductGroup() {
      let newList = this.productGroupList.map((item) => {
        if (this.ruleForm.groupId.includes(parseInt(item.id))) {
          item.quantity.push(this.storage.get("commodityLength"));
        }
        return item;
      });
      console.log("this.productGroupList==", newList);
      await setListGroup({ newList });
      this.cacheGroup();
    },
    // 改变产品组里面的产品id
    async changeGroup() {
      let newList = this.productGroupList.map((item) => {
        if (!this.ruleForm.groupId.includes(parseInt(item.id))) {
          item.quantity = item.quantity.filter(
            (child) => child != this.ruleForm.id
          );
        } else {
          if (!item.quantity.includes(this.ruleForm.id)) {
            item.quantity.push(this.ruleForm.id);
          }
        }
        return item;
      });
      console.log("this.productGroupList==", newList);
      await setListGroup({ newList });
      this.cacheGroup();
    },
    // 更新产品组缓存
    async cacheGroup() {
      getProductGroupList({
        page: 1,
        limit: 999,
      }).then((response) => {
        this.productGroupList = response.data;
        this.storage.set("productGroupList", response.data);
      });
    },
    toPage(id) {
      this.$router.push({
        path: "editGroup",
        query: { id },
      });
    },
    changeImageCover(e) {
      this.ruleForm.img = e;
    },
    changeImageDetail(e) {
      this.ruleForm.detailsImage = e;
    },
  },
};
</script>

<style lang="scss">
.title {
  background-color: rgba(248, 248, 248, 1);
  width: 100%;
  font-size: 24px;
  padding: 8px 20px;
  margin-bottom: 12px;
  //   width: 900px;
}
.content {
  padding: 20px 0;
}
.createProduct {
  .el-form-item {
    width: 900px;
  }
}
</style>
<style lang="scss">
.createProduct {
  .avatar {
    display: block;
  }
  .oldPrice span {
    color: #c0c4cc !important;
    text-decoration: line-through !important;
  }
  .sizeFont {
    font-size: 12px;
    color: #c0c4cc;
  }
  .cards {
    display: flex;
    flex-wrap: wrap;
    // justify-content: space-between;
    // width: 900px;
    .el-checkbox {
      align-items: center;
      display: flex;
      .el-checkbox__label {
        display: flex;
        align-items: center;
        .left {
          margin-right: 12px;
        }
      }
    }
    .demo {
      margin-right: 12px;
      width: 136px;
      display: flex;
      justify-content: center;
      flex-wrap: wrap;
      margin-bottom: 16px;
      padding: 12px 0;
      background-color: rgba(255, 255, 255, 1);
      border-width: 1px;
      border-style: solid;
      border-color: rgba(220, 221, 230, 1);
      border-radius: 3px;
      .card_h {
        width: 136px;
        height: 76px;
        text-align: center;
        img {
          width: 121px;
          border: 1px solid #666;
        }
      }
      .card_v {
        width: 136px;
        height: 121px;
        text-align: center;
        img {
          width: 76px;
          border: 1px solid #666;
          box-shadow: 5px 5px 2px #666;
        }
      }
    }
  }
}
</style>
